package trading_strategy.strategies;

import org.apache.log4j.Logger;
import trading_strategy.events.AbstractMarketEvent;
import trading_strategy.events.PublicTradeUpdate;
import trading_strategy.instruments.ListedInstrument;
import trading_strategy.orders.SingleOrderAutomaton;

/**
 * We have a valid signal. If some condition is met, we will trigger an order.
 * This PositionEnterer looks at the bid/ask and if it can hit at a certain level, it hit the order book
 *
 * <p/>
 * Created by IntelliJ IDEA.
 * User: gderoujoux
 * Date: 24 mai 2010
 * Time: 18:17:46
 * To change this template use File | Settings | File Templates.
 */
public class TargetPositionEnterer extends PositionTaker {

    // Direction of the trade to execute in order to enter the position

    double triggerPrice;
    double deactivatingPrice;
    long maxTsBeforeExit;

    public static final Logger LOGGER = Logger.getLogger(TargetPositionEnterer.class);

    public TargetPositionEnterer(PositionEntererListener strategy, ListedInstrument instrument, Direction direction, double triggerPrice, double deactivatingPrice, long maxTsBeforeExit, SingleOrderAutomaton automaton) {
        super(instrument, direction, strategy, automaton);
        this.triggerPrice = triggerPrice;
        this.deactivatingPrice = deactivatingPrice;
        this.maxTsBeforeExit = maxTsBeforeExit;
    }

    @Override
    public void onMarketEvent(AbstractMarketEvent event) {
        super.onMarketEvent(event);    //To change body of overridden methods use File | Settings | File Templates.
        if (lastOrderBook != null) {
            if (direction == Direction.BUY) {
                if (lastOrderBook.getBook().getAskDepth() > 0) {
                    if (lastOrderBook.getBook().getAsk(0) <= triggerPrice) {
                        hit(event.getTs());
                    }
                }
            } else if (direction == Direction.SELL) {
                if (lastOrderBook.getBook().getBidDepth() > 0) {
                    if (lastOrderBook.getBook().getBid(0) >= triggerPrice) {
                        hit(event.getTs());
                    }
                }
            }
        }
    }

    @Override
    protected void handleTrade(PublicTradeUpdate ptu) {
        if (ptu.getTs() > maxTsBeforeExit) {
            deactivated(ptu.getTs());
        } else {
            if (direction == Direction.BUY) {
                if (deactivatingPrice > 0 && ptu.getPrice() <= deactivatingPrice) {
                    deactivated(ptu.getTs());
                }
            } else if (direction == Direction.SELL) {
                if (deactivatingPrice > 0 && ptu.getPrice() >= deactivatingPrice) {
                    deactivated(ptu.getTs());
                }
            }
        }
    }

}